package org.idea.qiyu.framework.sqlsession.factory.mapping.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * 这部分的初始化逻辑是发生在BeanFactory初始化之后的阶段，此时已经有对应的数据源配置了
 *
 * @Author linhao
 * @Date created in 8:26 上午 2021/5/28
 */
@Configuration
@AutoConfigureBefore(MybatisAutoConfiguration.class)
public class SqlSessionFactoryAutoConfiguration implements BeanFactoryPostProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(SqlSessionFactoryAutoConfiguration.class);

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        Map<String, DruidDataSource> map = configurableListableBeanFactory.getBeansOfType(DruidDataSource.class);
        for (String datasourceName : map.keySet()) {
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setDataSource(map.get(datasourceName));
            try {
                SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
                String name = datasourceName + "SqlSessionFactory";
                configurableListableBeanFactory.registerSingleton(name, sqlSessionFactory);
                LOGGER.info("{} is registry success",name);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
